package com.zhipu.balance.ui.vm.home.revise

import `in`.xiandan.countdowntimer.CountDownTimerSupport
import `in`.xiandan.countdowntimer.OnCountDownTimerListener
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.revise.ReviseActivity
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit


/**
 * 天平校正
 */
class ReviseModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService),SerialPortListener{
    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")
    /**
     * 文字提示
     */
    var TextPrompt = ObservableField("")

    /**
     * 是否校准
     */
    var Calibration = ObservableField(false)

    /**
     * 取消校准
     */
    var uncalibrate = ObservableField(false)

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 倒计时
     */
    var mCountDownTimerSupport = CountDownTimerSupport(1000, 700);


    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 倒计时
         */
        mCountDownTimerSupport.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            /**
             * 间隔的回调
             *
             * @param millisUntilFinished 剩余的时间
             * @see [](https://developer.android.com/reference/android/os/CountDownTimer.onTick
            ) */
            override fun onTick(millisUntilFinished: Long) {

            }

            /**
             * 倒计时完成后的回调
             *
             * @see [](https://developer.android.com/reference/android/os/CountDownTimer.onFinish
            ) */
            override fun onFinish() {
                if(uncalibrate.get() == true){
                    /**
                     * 取消定标
                     */
                    OpenSerialPort.cancelCalibration()
                    //倒计时开始
                    mCountDownTimerSupport.reset()
                    mCountDownTimerSupport.start()
                }
            }

            /**
             * 手动停止计时器的回调
             */
            override fun onCancel() {

            }

        })
    }

    /**
     * 每隔milliseconds毫秒后执行next操作
     */
    fun milliseconds(){
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Long>{

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                if(peel.get() == false){
                    /**
                     * 重量輸出命令
                     */
                    OpenSerialPort.output()
                }

            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })
    }


    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            when (numericalValue) {
                Constants.SEND_GO_START -> {
                    InitializeUtils.getDefaultMaker()?.show("去皮成功")
                    println("去皮成功")
                    peel.set(false)
                }
                Constants.FARMAR_500 -> {
                    weighing.set("砝码500")
                    TextPrompt.set("请放砝码500")
                    /**
                     * 隐藏取消校准
                     */
                    uncalibrate.set(true)
                }
                Constants.FARMAR_1000 -> {
                    weighing.set("砝码1000")
                    TextPrompt.set("请放砝码1000")
                    /**
                     * 隐藏取消校准
                     */
                    uncalibrate.set(true)
                }
                Constants.FARMAR_2000 -> {
                    weighing.set("砝码2000")
                    TextPrompt.set("请放砝码2000")
                    /**
                     * 隐藏取消校准
                     */
                    uncalibrate.set(true)
                }
                Constants.FARMAR_3000 -> {
                    weighing.set("砝码3000")
                    TextPrompt.set("请放砝码3000")
                    /**
                     * 隐藏取消校准
                     */
                    uncalibrate.set(true)
                }
                Constants.CALIBRATION_500 -> {
                    //串口发送十六进制 33 0D 0A  标定500G 标定完成重新上电就好了
                    weighing.set("完成定标")
                    /**
                     * 校准
                     */
                    Calibration.set(false)
                }
                Constants.OVERLOAD -> {
                    weighing.set("超重")
                    TextPrompt.set("")
                }
                Constants.SEND_GET_COMMAND -> {
                    /**
                     * 校准
                     */
                    Calibration.set(false)
                }
                Constants.SHIELD -> {
                    weighing.set("校准中")
                    TextPrompt.set("校准中请稍等...")
                }
                else -> {
                    if(peel.get() == true){
                        /**
                         * 置零命令
                         */
                        OpenSerialPort.ZeroOrder()
                    }else if(Calibration.get() == true){
                        /**
                         * 校准
                         */
                        calibration()
                    }else if(uncalibrate.get() == true){
                        if(DisposeUtils.balanceCorrection(event) == "0.0"){
                            uncalibrate.set(false)

                        }
                        /**
                         * 取消定标
                         */
                        OpenSerialPort.cancelCalibration()
                    }else{
                        weighing.set(DisposeUtils.balanceCorrection(event))
                    }
                    /**
                     * 隐藏取消校准
                     */
                    uncalibrate.set(false)
                    /**
                     * 文字提示
                     */
                    TextPrompt.set("")
                }
            }
        }
    }


    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }


    /**
     * 取消校准
     */
    fun uncalibrate(){
        InitializeUtils.getDefaultMaker()?.show("正在取消定标请稍后")
        /**
         * 校准
         */
        Calibration.set(false)
        /**
         * 取消校准
         */
        uncalibrate.set(true)
        /**
         * 倒计时
         */
        mCountDownTimerSupport.reset()
        mCountDownTimerSupport.start()
    }


    /**
     * 校准
     */
    fun clickCalibration(){
        InitializeUtils.getDefaultMaker()?.show("正在校准请稍后")
        /**
         * 是否校准
         */
        Calibration.set(true)
        /**
         * 线性定标
         */
        calibration()
    }

    private fun calibration(){
        println("calibration")
        /**
         * 线性定标
         */
        var mLinearScaling = SPUtils.getInstance().getBoolean("LinearScaling",false);
        if(mLinearScaling){
            OpenSerialPort.calibration1000()
        }else{
            OpenSerialPort.Scaling500()
        }
    }






    /**
     * 主菜单
     */
    fun mainMenu(){
        ActivityUtils.finishActivity(ReviseActivity::class.java)
    }
}